package com.wtx.fitness.service.impl;

import com.wtx.fitness.common.LoginDTO;
import com.wtx.fitness.common.LoginVO;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.entity.Admin;
import com.wtx.fitness.entity.Student;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.mapper.AdminMapper;
import com.wtx.fitness.mapper.StudentMapper;
import com.wtx.fitness.service.UserService;
import com.wtx.fitness.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private AdminMapper adminMapper;

  /**
   * 用户登录
   */
  @Override
  public LoginVO login(LoginDTO loginDTO) {
    // 判断登录类型
    if ("admin".equals(loginDTO.getType())) {
      // 管理员登录
      Admin admin = adminMapper.login(loginDTO.getUsername(), loginDTO.getPassword());
      if (admin == null) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "用户名或密码错误");
      }

      // 生成token
      String token = JwtUtil.generateToken(
          admin.getId().toString(), "admin");

      // 构建返回数据
      LoginVO loginVO = new LoginVO();
      loginVO.setId(admin.getId());
      loginVO.setUsername(admin.getUsername());
      loginVO.setName(admin.getName());
      loginVO.setType("admin");
      loginVO.setToken(token);
      loginVO.setAvatarUrl(admin.getAvatarUrl());

      return loginVO;
    } else if ("student".equals(loginDTO.getType())) {
      // 学生登录
      Student student = studentMapper.login(loginDTO.getUsername(), loginDTO.getPassword());
      if (student == null) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "学号或密码错误");
      }

      // 生成token
      String token = JwtUtil.generateToken(
          student.getStuId(), "student");

      // 构建返回数据
      LoginVO loginVO = new LoginVO();
      loginVO.setId(Integer.valueOf(student.getStuId()));
      loginVO.setUsername(student.getStuId());
      loginVO.setName(student.getName());
      loginVO.setType("student");
      loginVO.setToken(token);
      loginVO.setAvatarUrl(student.getAvatarUrl());

      return loginVO;
    } else {
      throw new BusinessException(ResultCode.PARAM_ERROR, "无效的登录类型");
    }
  }
}